package com.matt.service.impl;

import com.matt.commons.exception.BusinessException;
import com.matt.domain.*;
import com.matt.foundation.constant.ClienteleConstant;
import com.matt.foundation.constant.LeadsConstant;
import com.matt.foundation.model.ErrorCode;
import com.matt.foundation.query.LeadsHistoryQuery;
import com.matt.foundation.utils.DateUtil;
import com.matt.foundation.vo.LeadsHistoryVo;
import com.matt.repository.*;
import com.matt.repository.base.LeadsHistoryNativeRepository;
import com.matt.repository.base.LeadsNativeRepository;
import com.matt.service.AnalysisService;
import com.matt.service.LeadsHistoryService;
import com.matt.remoteCall.SsoCallService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Objects;

import static com.matt.foundation.constant.OperateConstant.OPERATE_FOLLOW;

/**
 * **********************
 * Created by Ron
 * from com.matt
 * on 2018/6/13 0013.
 * *********************
 */
@Service
public class LeadsHistoryServiceImpl implements LeadsHistoryService {

    @Autowired
    private LeadsHistoryRepository leadsHistoryRepository;
    @Autowired
    private LeadsRepository leadsRepository;
    @Autowired
    private ClienteleRepository clienteleRepository;
    @Autowired
    private SsoCallService ssoCallService;
    @Autowired
    private LeadsNativeRepository leadsNativeRepository;
    @Autowired
    private LeadsHistoryNativeRepository leadsHistoryNativeRepository;

    @Autowired
    private AboutPalletRepository aboutPalletRepository;

    @Autowired
    private AboutVisitRepository aboutVisitRepository;

    @Autowired
    private AnalysisService analysisService;


    @Override
    public LeadsHistory saveVisit(String imgUrl, LeadsHistory leadsHistory){
        Date date = new Date();
        leadsHistory.setOperationType(OPERATE_FOLLOW);
        String lineSeparator = System.lineSeparator();
        //修改到访试托下次跟进时间
        if(leadsHistory.getType().equals("aboutPallet")){
            //试托
            AboutPallet aboutPallet = aboutPalletRepository.getOne(leadsHistory.getLeadsId());
            aboutPallet.setNextTime(leadsHistory.getNextTime());
            aboutPallet.setStatus(1);
            aboutPallet.setVisitTime(leadsHistory.getPalletTime());
            aboutPalletRepository.save(aboutPallet);
            if(StringUtils.isNotBlank(leadsHistory.getContent())){
                leadsHistory.setContent("跟进内容：在 " + DateUtil.dateToymd(date) + " 跟进了本条数据："+lineSeparator+"跟进内容：" + leadsHistory.getContent()+lineSeparator+"下次跟进时间："+DateUtil.dateToymd(leadsHistory.getPalletTime()));
            }else{
                leadsHistory.setContent("在 " + DateUtil.dateToymd(date) + " 跟进了本条数据"+lineSeparator+"跟进内容："+lineSeparator+"下次跟进时间："+DateUtil.dateToymd(leadsHistory.getPalletTime()));
            }
        }

        if(leadsHistory.getType().equals("aboutVisit")){
            //到访
            AboutVisit  aboutVisit = aboutVisitRepository.getOne(leadsHistory.getLeadsId());
            aboutVisit.setNextTime(leadsHistory.getNextTime());
            aboutVisit.setStatus(1);
            aboutVisit.setVisitTime(leadsHistory.getVisitTime());
            //如果预约，增加一条预约记录
            if(leadsHistory.getIsPallet()!=null && leadsHistory.getIsPallet()==1){
                AboutPallet aboutPallet = new AboutPallet();
                BeanUtils.copyProperties(aboutVisit,aboutPallet);
                AboutPallet aboutPallet1 = aboutPalletRepository.findByMobileAreaId(aboutPallet.getMobile(),aboutPallet.getAreaId());
                if(Objects.isNull(aboutPallet1)){
                    aboutPallet.setCreated(new Date());
                    aboutPallet.setStatus(2);
                    aboutPallet.setVisitTime(leadsHistory.getPalletTime());
                    //下次跟进时间
                    aboutPallet.setNextTime(null);
                    if(Objects.isNull(aboutVisit.getGender())){
                        aboutVisit.setGender(2);
                    }
                    aboutPalletRepository.save(aboutPallet);
                }else{
                    //修改预约时间，状态
                    aboutPallet1.setStatus(2);
                    //预约试托时间
                    aboutPallet1.setVisitTime(leadsHistory.getPalletTime());
                    //下次跟进时间
                    aboutPallet1.setNextTime(null);
                    if(Objects.isNull(aboutVisit.getGender())){
                        aboutVisit.setGender(2);
                    }
                    aboutPalletRepository.save(aboutPallet1);
                }
            }
            aboutVisitRepository.save(aboutVisit);
            if(StringUtils.isNotBlank(leadsHistory.getContent())){
                leadsHistory.setContent("跟进内容：在 " + DateUtil.dateToymd(date) + " 跟进了本条数据："+ lineSeparator+"跟进内容："+ leadsHistory.getContent()+lineSeparator+"下次跟进时间："+DateUtil.dateToymd(leadsHistory.getVisitTime()));
            }else{
                leadsHistory.setContent("在 " + DateUtil.dateToymd(date) + " 跟进了本条数据"+lineSeparator+"跟进内容："+lineSeparator+"下次跟进时间："+DateUtil.dateToymd(leadsHistory.getVisitTime()));
            }
        }
        leadsHistory.setStaffHeadImgUrl(imgUrl);
        leadsHistory.setActualFollowDate(new Date());
        LeadsHistory leadsHistoryVo = leadsHistoryRepository.save(leadsHistory);
        return leadsHistoryVo;
    }


    @Override
    public LeadsHistory save(String imgUrl, LeadsHistory leadsHistory) {
        Leads leads = leadsRepository.findByIdAndAreaId(leadsHistory.getLeadsId(), leadsHistory.getAreaId());
        if(leads == null){
            throw new BusinessException(ErrorCode.LEADS_NOT_EXIST, "线索不存在");
        }

        String tempContent = leadsHistory.getContent();
        Date date = new Date();
        leadsHistory.setOperationType(OPERATE_FOLLOW);
        leadsHistory.setActualFollowDate(date);
        if(StringUtils.isNotBlank(leadsHistory.getContent())){
            leadsHistory.setContent( leadsHistory.getContent() );
        }else{
            leadsHistory.setContent("");
        }
        leadsHistory.setStaffHeadImgUrl(imgUrl);
        LeadsHistory leadsHistoryVo = leadsHistoryRepository.save(leadsHistory);

        /**
         * leadsId：线索id不为空，则更新线索中的跟进状态
         * clientelesId：客户id不为空，则更新客户中的跟进状态
         */
        if (StringUtils.isNotBlank(leadsHistory.getLeadsId()) && StringUtils.isBlank(leadsHistory.getClientelesId())) {
            leads.setZhwysStatus("1");
            leads.setRankp(leadsHistory.getRankp());
            leads.setNextTime(leadsHistory.getNextTime());
            leads.setChannel(leadsHistory.getChannel());
            leads.setStatus(leadsHistory.getLeadsStatus());
            leads.setLastFollowTime(new Date());
            leads.setStatus(leadsHistory.getLeadsStatus());
            leads.setClientStatus(leadsHistory.getClientStatus());
            leads.setChannStatus(leadsHistory.getClientStatus());
            leads.setLastFollowRecord(tempContent);
            Leads result = leadsRepository.save(leads);
            if(Objects.isNull(result)){
                throw new BusinessException(ErrorCode.LEADS_NOT_EXIST, "没有完成修改");
            }
            //增加一条试托
            if(leadsHistory.getIsPallet()!=null && leadsHistory.getIsPallet()==1){
                AboutPallet aboutPallet = new AboutPallet();
                BeanUtils.copyProperties(leads,aboutPallet);
                AboutPallet aboutPallet1 = aboutPalletRepository.findByMobileAreaId(aboutPallet.getMobile(),aboutPallet.getAreaId());
                if(Objects.isNull(aboutPallet1)){
                    aboutPallet.setCreated(new Date());
                    aboutPallet.setStatus(2);
                    aboutPallet.setVisitTime(leadsHistory.getPalletTime());
                    //下次跟进时间
                    aboutPallet.setNextTime(null);
                    aboutPalletRepository.save(aboutPallet);
                }else{
                    //修改预约时间，状态
                    aboutPallet1.setStatus(2);
                    //预约试托时间
                    aboutPallet1.setVisitTime(leadsHistory.getPalletTime());
                    //下次跟进时间
                    aboutPallet1.setNextTime(null);
                    aboutPalletRepository.save(aboutPallet1);
                }
            }

            //增加一条到访
            if(leadsHistory.getIsVisit()!=null && leadsHistory.getIsVisit()==1){
                AboutVisit aboutVisit = new AboutVisit();
                BeanUtils.copyProperties(leads,aboutVisit);
                AboutVisit aboutVisit1 = aboutVisitRepository.findByMobileAreaId(aboutVisit.getMobile(),aboutVisit.getAreaId());
                if(Objects.isNull(aboutVisit1)){
                    aboutVisit.setCreated(new Date());
                    aboutVisit.setStatus(2);
                    aboutVisit.setVisitTime(leadsHistory.getVisitTime());
                    //下次跟进时间
                    aboutVisit.setNextTime(null);
                    aboutVisit.setRemark(leadsHistory.getRemark());
                    aboutVisitRepository.save(aboutVisit);
                }else{
                    //修改预约时间，状态
                    aboutVisit1.setStatus(2);
                    //预约到访时间
                    aboutVisit1.setVisitTime(leadsHistory.getVisitTime());
                    //下次跟进时间
                    aboutVisit1.setNextTime(null);
                    aboutVisitRepository.save(aboutVisit1);
                }
            }
        }else
        //如果跟进的是客户对象， 则需要变更客户的状态
        if (StringUtils.isNotBlank(leadsHistory.getClientelesId())) {
            Clientele clientele = clienteleRepository.getOne(leadsHistory.getClientelesId());

            leadsHistoryVo.setStatus(leadsHistory.getClienteleStatus());
            leadsHistoryVo.setSignStatus(clientele.getSignStatus());

            if(leadsHistory.getClienteleStatus() == ClienteleConstant.Status.OTHER.codeOf()) {
                leadsHistoryVo.setStatusVal(leadsHistory.getStatusVal());
                clienteleRepository.updateStatus(leadsHistory.getClientelesId(), leadsHistory.getClienteleStatus(), leadsHistory.getStatusVal(), tempContent);
            }else{
                leadsHistoryVo.setStatusVal(getStatusVal(leadsHistory.getClienteleStatus()));
                clienteleRepository.updateStatus(leadsHistory.getClientelesId(), leadsHistory.getClienteleStatus(), getStatusVal(leadsHistory.getClienteleStatus()), tempContent);
            }
        }

        // 添加主动例子到访数
        if (leadsHistory.getLeadsStatus() >= LeadsConstant.Status.ARRIVED.codeOf()
                || (leadsHistory.getClienteleStatus() >= ClienteleConstant.Status.ARRIVED.codeOf() && leadsHistory.getClienteleStatus() < ClienteleConstant.Status.OTHER.codeOf() )) {
            analysisService.arrival(leadsHistory.getLeadsId(), leads.getCategory(), leads.getChannelId(), leadsHistory.getAreaId(), leadsHistory.getStaffId(), date);
        }

        return leadsHistoryVo;
    }

    @Override
    public Page<LeadsHistoryVo> findByLeadsId(String leadsId, LeadsHistoryQuery leadsHistoryQuery) {
        List<LeadsHistoryVo> list = leadsHistoryNativeRepository.findByLeadsIdAndType(leadsId, "leads", leadsHistoryQuery);
        Long count = leadsHistoryNativeRepository.count(leadsId, "leads", leadsHistoryQuery);
        return new PageImpl<LeadsHistoryVo>(list,  PageRequest.of(leadsHistoryQuery.getPageNum(), leadsHistoryQuery.getPageSize()), count);
    }


    @Override
    public Page<LeadsHistoryVo> findByVisitId(String leadsId, LeadsHistoryQuery leadsHistoryQuery) {
        List<LeadsHistoryVo> list = leadsHistoryNativeRepository.findByVisit(leadsId, leadsHistoryQuery.getType(), leadsHistoryQuery);
        Long count = leadsHistoryNativeRepository.visitcount(leadsId, leadsHistoryQuery.getType(), leadsHistoryQuery);
        return new PageImpl<LeadsHistoryVo>(list,  PageRequest.of(leadsHistoryQuery.getPageNum(), leadsHistoryQuery.getPageSize()), count);
    }


    @Override
    public Page<LeadsHistoryVo> findByPalletId(String leadsId, LeadsHistoryQuery leadsHistoryQuery) {
        List<LeadsHistoryVo> list = leadsHistoryNativeRepository.findByPallet(leadsId, leadsHistoryQuery.getType(), leadsHistoryQuery);
        Long count = leadsHistoryNativeRepository.palletcount(leadsId, leadsHistoryQuery.getType(), leadsHistoryQuery);
        return new PageImpl<LeadsHistoryVo>(list,  PageRequest.of(leadsHistoryQuery.getPageNum(), leadsHistoryQuery.getPageSize()), count);
    }


    @Override
    public Page<LeadsHistoryVo> findByClienteleId(String clientelesId, LeadsHistoryQuery leadsHistoryQuery) {
        List<LeadsHistoryVo> list = leadsHistoryNativeRepository.findByClienteledIdAndType(clientelesId, "clientele", leadsHistoryQuery);
        Long count = leadsHistoryNativeRepository.countByClienteleId(clientelesId, "clientele", leadsHistoryQuery);
        return new PageImpl<LeadsHistoryVo>(list,  PageRequest.of(leadsHistoryQuery.getPageNum(), leadsHistoryQuery.getPageSize()), count);
    }

    @Override
    public Page<LeadsHistoryVo> findAll(String clientelesId, LeadsHistoryQuery leadsHistoryQuery) {
        Clientele clientele = clienteleRepository.getOne(clientelesId);
        List<LeadsHistoryVo> list = leadsHistoryNativeRepository.findAll(clientele.getLeadsId(), leadsHistoryQuery);
        Long count = leadsHistoryNativeRepository.countAll(clientele.getLeadsId(), leadsHistoryQuery);
        return new PageImpl<LeadsHistoryVo>(list,  PageRequest.of(leadsHistoryQuery.getPageNum(), leadsHistoryQuery.getPageSize()), count);
    }


    public static String getStatusVal(Integer status) {
        if (status != null) {
            switch (status) {
                case 1:
                    return ClienteleConstant.Status.NON_HANDLE.valueOf();
                case 2:
                    return ClienteleConstant.Status.ORDERED.valueOf();
                case 3:
                    return ClienteleConstant.Status.ARRIVED.valueOf();
                case 4:
                    return ClienteleConstant.Status.FINISH_APPLY_TABLE.valueOf();
                case 5:
                    return ClienteleConstant.Status.ORDER_CASH.valueOf();
                case 6:
                    return ClienteleConstant.Status.ORDER_CASH.valueOf();
                case 7:
                    return ClienteleConstant.Status.NON_PASS_INTERVIEW.valueOf();
                case 8:
                    return ClienteleConstant.Status.DISAGREE_IDEA.valueOf();
                case 9:
                    return ClienteleConstant.Status.DISAGREE_AREA.valueOf();
                case 10:
                    return ClienteleConstant.Status.NON_PAY_ABILITY.valueOf();
                case 11:
                    return ClienteleConstant.Status.SUCCESS.valueOf();
                case 12:
                    return ClienteleConstant.Status.OTHER.valueOf();
            }
        }
        return "";
    }
}
